// pages/main/index.js
let mta = require('../../utils/mta_analysis.js');
Page({
    data: {
        msg: '请扫码开门或定位门店',
        isLoading: true,
        urlAddress: getApp().globalData.imageUrl,
        isFirst: true,
        isShow: false,
        openid: '',
        userInfo: {},
    },
    onLoad: function(options) {
        //埋点
        mta.Page.init();
        mta.Event.stat("smg_shouye", {});
        mta.Event.stat("smg_loding", {})
        // this.getWiFi();


        console.log('*****' + options.q)
        if (options.q) {

           var scan_url = decodeURIComponent(options.q);
            //var scan_url = 'https://go.24xiaomai.com/html5/xiaomaipu.html?shopCode=XM0002&ST=4&GBK=6931925828025';
            //var scan_url = 'https://go.24xiaomai.com/html5/xiaomaipu.html?shopCode=XM0201&deviceCode=XM0201SY001';
             //店铺 开门的
            //var scan_url = 'https://tgo.24xiaomai.com/auth.do?shopCode=TS0008&souce=1';

            // var scan_url = decodeURIComponent(options.q);
            // var scan_url = 'https://go.24xiaomai.com/html5/xiaomaipu.html?shopCode=XM0201&ST=4&GBK=6921355232615';
            //var scan_url = 'https://go.24xiaomai.com/html5/xiaomaipu.html?shopCode=TS0013&deviceCode=TS0013SY001';

            var args = this.fitUrl(scan_url);

            //console.log("三码合一进入")
            // console.log('三码合一进入==' + scan_url)
            var shopCode = args.shopCode; //商店名称
            var type = args.souce; //是否开门  0开门，1不开门
            var shopType = args.ST; //shopType门店类型  4普通
            var recommendId = args.recommendId; //推荐人id
            var groupCode = args.groupCode; //团id、
            var deviceCode = args.deviceCode; //机器id
            var gbk = args.GBK; //商品GBK
            if (args.GC) {
                var goodsCode = args.GC.split("_")[1]; //商品id
                var categoryCode = args.GC.split("_")[0];
            }
            getApp().globalData.common.shopCode = shopCode;
            getApp().globalData.common.reserveShopCode = shopCode;
            getApp().globalData.common.souce = type;
            getApp().globalData.common.TS = shopType;
            getApp().globalData.common.deviceCode = deviceCode; //机器id
            getApp().globalData.common.groupCode = groupCode;
            getApp().globalData.common.recommendId = recommendId;
            getApp().globalData.common.goodsCode = goodsCode;
            getApp().globalData.common.categoryCode = categoryCode;
            getApp().globalData.common.gbk = gbk; //商品码
            console.log("getApp().globalData.common.gbk")
            console.log(getApp().globalData.common.gbk)
            wx.setStorageSync('shopCode', shopCode);
        }

        //判断是否有用户缓存
        if (wx.getStorageSync('openId')) {
            if (wx.getStorageSync('newUser')) {
                console.log(wx.getStorageSync('newUser'))
            } else {
                //console.log('老用户')
                this.setData({
                    isFirst: false
                });
                this.appletLogin();
            }
        } else {
            this.getUserId();
        }

    },
    onReady: function() {
    },
    onShow: function() {
        // 页面显示
        // console.log(122131233)

    },
    onHide: function() {
        // 页面隐藏
    },
    onUnload: function() {
        // 页面关闭
    },
    //
    getUserId: function() {
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        var _self = this;
        wx.login({
            success: function(res) {
                wx.hideLoading();
                if (res.code) {
                    var code = res.code;
                    console.log(code);
                    // return;
                    _self.acquireOpenId(code)
                } else {

                }
            },
            fail: function(res) {
                console.log(res)
            }
        });

    },
    //用code获取openId,是否是新用户,并缓存 
    acquireOpenId: function(code) {
        var _self = this;
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        wx.request({
            // url: getApp().globalData.baseUrl + '/appletOpenId.do',
            url: getApp().globalData.baseUrl + '/applet/autoLogin.do',
            data: {
                code: code
            },
            success: function(response) {
                wx.hideLoading();
                const res = response.data
                if (res.code == 200) {
                    if (res.obj.first) {
                        _self.setData({
                            isFirst: true,
                            openid: res.obj.openId
                        });
                        getApp().globalData.userInfo = res.obj;
                        wx.setStorageSync('openId', res.obj.openId);
                        wx.setStorageSync('newUser', true);
                        _self.getUserInfo();
                    } else {
                        //老用户   
                        _self.setData({
                            isFirst: false,
                            openid: res.obj.openId
                        });
                        getApp().globalData.userInfo = res.obj;
                        getApp().globalData.header.Cookie = 'SESSION=' + res.obj.session;
                        wx.setStorageSync('openId', res.obj.openId);
                        wx.setStorageSync('memberId', res.obj.memId);
                        console.log('getApp().globalData.common.groupCode')
                        console.log(getApp().globalData.common.TS)
                        if (getApp().globalData.common.deviceCode || getApp().globalData.common.TS == 4) {
                            const version = wx.getSystemInfoSync().SDKVersion;
                            if (_self.compareVersion(version, '2.1.0') != -1) {
                                wx.navigateTo({
                                    url: '../newScan/newScan'
                                })
                            } else {
                                wx.navigateTo({
                                    url: '../scan/scan'
                                })
                            }
                            return
                        }
                        if (getApp().globalData.common.groupCode) { //如果有团号直接跳转团详情
                            wx.redirectTo({
                                url: '../myGroupDetail/myGroupDetail?groupCode=' + getApp().globalData.common.groupCode
                            })
                            return
                        }
                        if (getApp().globalData.common.TS == 2 || getApp().globalData.common.souce == 3) {
                            wx.switchTab({
                                url: '../reserve/reserve' //外卖
                            })
                            return

                        } else if (getApp().globalData.common.TS == 4) {
                            const version = wx.getSystemInfoSync().SDKVersion;
                            if (_self.compareVersion(version, '2.1.0') != -1) {
                                wx.navigateTo({
                                    url: '../newScan/newScan'
                                })
                            } else {
                                wx.navigateTo({
                                    url: '../scan/scan'
                                })
                            }
                            return

                        } else if (getApp().globalData.common.TS == 0) {
                            wx.switchTab({
                                url: '../group/group' //拼团
                            })
                            return
                        } else if (getApp().globalData.common.souce == 0 || getApp().globalData.common.souce == 1) {
                            wx.switchTab({
                                url: '../index/index' //开门
                            })
                            return
                        } else {
                            wx.switchTab({
                                //url: '../newIndex/newIndex' //新首页
                                url: '../reserve/reserve'
                            })
                        }
                    }
                    return
                } else {
                    _self.setData({
                        isFirst: false
                    });
                    _self.showMyToast(_self, res.des)
                }
            }
        })
    },
    //老用户根据openid登录
    appletLogin: function() {
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        var _self = this
        wx.request({
            url: getApp().globalData.baseUrl + '/applet/login.do',
            method: 'get',
            data: {
                openId: wx.getStorageSync('openId'),
            },
            success: function(res) {
                wx.hideLoading();
                if (res.data.code == 200) {
                    getApp().globalData.userInfo = res.data.obj;
                    getApp().globalData.header.Cookie = 'SESSION=' + res.data.obj.session;
                    if (getApp().globalData.common.deviceCode || getApp().globalData.common.TS == 4) {
                        const version = wx.getSystemInfoSync().SDKVersion;
                        if (_self.compareVersion(version, '2.1.0') != -1) {
                            wx.navigateTo({
                                url: '../newScan/newScan'
                            })
                        } else {
                            wx.navigateTo({
                                url: '../scan/scan'
                            })
                        }
                        return
                    }
                    if (getApp().globalData.common.groupCode) { //如果有团号直接跳转团详情
                        wx.redirectTo({
                            url: '../myGroupDetail/myGroupDetail?groupCode=' + getApp().globalData.common.groupCode
                        })
                        return
                    }
                    if (getApp().globalData.common.TS == 2 || getApp().globalData.common.souce == 3) {
                        wx.switchTab({
                            url: '../reserve/reserve' //外卖
                        })
                        return

                    } else if (getApp().globalData.common.TS == 0) {
                        wx.switchTab({
                            url: '../group/group' //拼团
                        })
                        return
                    } else if (getApp().globalData.common.souce == 0 || getApp().globalData.common.souce == 1) {
                        wx.switchTab({
                            url: '../index/index' //开门
                        })
                        return
                    } else { 
                        wx.switchTab({
                           // url: '../newIndex/newIndex' //新首页
                           url: '../reserve/reserve'
                        })
                    }
                } else {
                    _self.loadingErr();
                    _self.setData({
                        isFirst: false
                    });
                    _self.showMyToast(_self, res.data.des, 5000)
                }
            }
        })
    },

    //获取用户信息
    getUserInfo: function() {

        this.setData({
            userInfo: null
        })
        getApp().globalData.userInfo.nickName = "";
        getApp().globalData.userInfo.avatarUrl = "";
        getApp().globalData.userInfo.gender = "";

    },
    //获取用户手机号
    getPhoneNumber: function(e) {
        mta.Event.stat("smg_zhuce", {});
        if (!e.detail.iv || !e.detail.encryptedData) {
            mta.Event.stat("smg_btbushouquanshouji", {});
            this.loadingErr();
        } else {
            mta.Event.stat("smg_btshouquanshouji", {});
            this.decryption(wx.getStorageSync('openId'), e.detail.iv, e.detail.encryptedData);
        }

    },
    //手机号解密、注册
    decryption: function(id, iv, encryptedData) {
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        var _self = this;
        wx.request({
            url: getApp().globalData.baseUrl + '/applet/decryptMobile.do',
            method: 'post',
            header: getApp().globalData.header,
            data: {
                openId: id,
                iv: iv,
                encryptedData: encryptedData,
                platform: 6,
                shopCode: getApp().globalData.common.shopCode,
                userInfo: _self.data.userInfo,
                recommendId: getApp().globalData.common.recommendId
            },
            success: function(res) {
                wx.hideLoading();
                if (res.data.code == 200) {
                    _self.setData({
                        isFirst: false
                    });
                    wx.setStorageSync('newUser', false);
                    getApp().globalData.userInfo = res.data.obj;
                    // getApp().globalData.userInfo.memId = res.data.obj.memId;
                    // getApp().globalData.userInfo.nickName = res.data.obj.nickName;
                    // getApp().globalData.userInfo.avatarUrl = res.data.obj.avatarUrl;
                    // getApp().globalData.userInfo.gender = res.data.obj.gender;
                    // getApp().globalData.userInfo.level = res.data.obj.level;
                    // getApp().globalData.userInfo.isBind = res.data.obj.isBind;
                    getApp().globalData.header.Cookie = 'SESSION=' + res.data.obj.session;
                    if (getApp().globalData.common.deviceCode || getApp().globalData.common.TS == 4) {
                        const version = wx.getSystemInfoSync().SDKVersion;
                        if (_self.compareVersion(version, '2.1.0') != -1) {
                            wx.navigateTo({
                                url: '../newScan/newScan'
                            })
                        } else {
                            wx.navigateTo({
                                url: '../scan/scan'
                            })
                        }
                        return
                    }
                    if (getApp().globalData.common.groupCode) { //如果有团号直接跳转团详情
                        wx.redirectTo({
                            url: '../myGroupDetail/myGroupDetail?groupCode=' + getApp().globalData.common.groupCode
                        })
                        return
                    }

                    if (getApp().globalData.common.TS == 2 || getApp().globalData.common.souce == 3) {
                        wx.switchTab({
                            url: '../reserve/reserve'
                        })
                        return
                    } else if (getApp().globalData.common.TS == 1) {
                        wx.switchTab({
                            url: '../newReserve/newReserve'
                        })
                        return
                    } else if (getApp().globalData.common.souce == 0 || getApp().globalData.common.souce == 1) {
                        wx.switchTab({
                            url: '../index/index'
                        })
                        return
                    } else {
                        wx.switchTab({
                            //url: '../newIndex/newIndex'
                            url: '../reserve/reserve'
                        })
                    }



                } else if (res.data.code == 999) {
                    _self.showMyToast(_self, res.data.des, 5000)
                } else {
                    _self.loadingErr();

                }
            }
        })

    },
    showMyToast: function(self, my_toast_tip, time = 2000, template = 'my_toast') {
        self.setData({
            template: template, //my_toast
            my_toast_tip: my_toast_tip
        })
        setTimeout(() => {
            self.setData({
                template: '', //my_toast
                my_toast_tip: ''
            })
        }, time)
    },
    turnAction: function() {
        mta.Event.stat("smg_btjiazaitiaoguo", {});
        getApp().globalData.common.shopCode = null;
        wx.switchTab({
            url: '../index/index'
        })
    },
    loadingErr: function() {
        wx.navigateTo({
            url: '../login/login'
        })
    },
    fitUrl: function(url) {
        var res = "?" + url.split('?')[1];
        var qs = (res.length > 0 ? res.substring(1) : ""),
            args = {},
            items = qs.length ? qs.split("&") : [],
            item = null,
            name = null,
            value = null,
            i = 0,
            len = items.length;
        for (i = 0; i < len; i++) {
            item = items[i].split("=");
            name = decodeURIComponent(item[0]);
            value = decodeURIComponent(item[1]);
            if (name.length) {
                args[name] = value;
            }
        }
        return args;
    },
    compareVersion: function(v1, v2) {
        v1 = v1.split('.')
        v2 = v2.split('.')
        const len = Math.max(v1.length, v2.length)

        while (v1.length < len) {
            v1.push('0')
        }
        while (v2.length < len) {
            v2.push('0')
        }

        for (let i = 0; i < len; i++) {
            const num1 = parseInt(v1[i])
            const num2 = parseInt(v2[i])

            if (num1 > num2) {
                return 1
            } else if (num1 < num2) {
                return -1
            }
        }

        return 0
    },

})